/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package dev.ahamed.mva.sample.util;

import ohos.agp.colors.RgbColor;
import ohos.agp.components.element.Element;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;

/**
 * Utils
 *
 * @since 2021.07.08
 */
public class Utils {
    /**
     * 格式化vp
     *
     * @param dimens vp/fp值
     * @return 格式化后的值
     */
    public static float parseDimension(String dimens) {
        float dimensFloat = 0f;
        String newDimens = dimens.replace("vp", "").replace("fp", "");
        try {
            dimensFloat = Float.parseFloat(newDimens);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return dimensFloat;
    }

    /**
     * vp转px
     *
     * @param context 上下文
     * @param dimens vp值
     * @return px
     */
    public static int vp2px(Context context, String dimens) {
        float vpValue = parseDimension(dimens);
        Display display = DisplayManager.getInstance().getDefaultDisplay(context).get();
        float dpi = display.getAttributes().densityPixels;
        return (int) (vpValue * dpi + 0.5d);
    }

    /**
     * 获取Element
     *
     * @param color 颜色
     * @param radius 弧度
     * @return Element
     */
    public static Element getElementByColorRadius(RgbColor color, float radius) {
        ShapeElement drawable = new ShapeElement();
        drawable.setShape(0);
        drawable.setRgbColor(color);
        drawable.setCornerRadius(radius);
        return drawable;
    }

    /**
     * 获取屏幕宽度
     *
     * @param context 上下文
     * @return 屏幕宽度
     */
    public static int getDisplayWidthInPx(Context context) {
        Display display = DisplayManager.getInstance().getDefaultDisplay(context).get();
        return display.getAttributes().width;
    }

    /**
     * 获取屏幕高度
     *
     * @param context 上下文
     * @return 屏幕高度
     */
    public static int getDisplayHeightInPx(Context context) {
        Display display = DisplayManager.getInstance().getDefaultDisplay(context).get();
        return display.getAttributes().height;
    }

}
